package com.xjtu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xjtu.config.SocketManager;
import com.xjtu.model.Call;
import com.xjtu.repository.CallRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;


@ServerEndpoint("/call/{id}")
@Controller
@Slf4j
public class WSController {
    @Resource
    private CallRepository callRepository;


    private Call record;


    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id) {
        SocketManager.addSession(id, session);
    }


    @OnClose
    public void onClose(Session session) {
        SocketManager.removeSession(session.getId());
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("message: {}",message);
        JSONObject data = JSON.parseObject(message);

        String type = data.getString("type");
        JSONObject user = data.getJSONObject("message");
        String from = user.getString("userId");
        String to = user.getString("toUserId");

        log.info(type);
        if (Objects.equals(type, "connect") || Objects.equals(type, "ask")) {
            //被呼叫方当前不在线
            log.info(message);
            if (SocketManager.getUser(to) == null) {
                data.put(type, "offline");
                SocketManager.sendMessage(from, data.toJSONString());
                return;
            }
        }
        SocketManager.sendMessage(to, message);
    }


    @OnError
    public void onError(Session session, Throwable throwable) {
        String id = SocketManager.findIdBySessionId(session.getId());
        log.error("用户session出错：{}", id);
        log.error("webSocket错误：{}", throwable.getMessage());
        SocketManager.removeSession(session.getId());
    }
}